import logging
import json
import yaml
import requests
from auto.apiSecurity.common.basic import process_input, check_release_id


def add_mock_open(env, api_version_id, mockConfig, mockOpen, apiName):
    if mockOpen == 1:
        with open('data/config/token.yml', 'r') as f:
            config = yaml.safe_load(f)
        with open('data/config/config.yaml', 'r') as f2:
            config_data = yaml.safe_load(f2)
        with open('data/config/project_id.txt', 'r') as f3:
            project_id = f3.read().strip()
        with open('data/config/api_id.txt', 'r') as f4:
            api_id = f4.read().strip()

        url = config_data['environments'][env]['host'] + config_data['environments'][env][
            'add_mock_open'] + api_id + "/versions/" + api_version_id + "/mock"
        # print(url)
        token = config['token']
        headers = {'Content-Type': 'application/json', 'version': '2.0', 'Authorization': token, 'Tenantid': project_id,
                   'X-Request-Method': 'PUT'}
        query_params = {
        }
        data = process_input(mockConfig)
        # print(data)
        try:
            # 发送 打开 POST 请求
            response = requests.post(url, data=data, headers=headers, params=query_params)
            # 检查响应状态
            response.raise_for_status()  # 如果响应状态码不是 200，抛出异常
            parsed_data = response.json()
            logging.info("成功----接口有响应，响应数据：%s", json.dumps(parsed_data, ensure_ascii=False))
        except requests.exceptions.RequestException as e:
            logging.error("请求失败: %s", str(e))
        except json.JSONDecodeError:
            logging.error("解析 JSON 响应失败")
        release_id = check_release_id(env, apiName)
        url2 = config_data['environments'][env]['host'] + config_data['environments'][env][
            'check_release_id'] + '/' + release_id + '/mock/enable'
        headers2 = {'Content-Type': 'application/json', 'version': '2.0', 'Authorization': token, 'Tenantid': project_id}
        try:
            # 发送 Mock的POST 请求
            response = requests.post(url2, data=None, headers=headers2, params=query_params)
            # 检查响应状态
            response.raise_for_status()  # 如果响应状态码不是 200，抛出异常
            parsed_data = response.json()
            logging.info("成功----Mock开启成功：%s", json.dumps(parsed_data, ensure_ascii=False))
        except requests.exceptions.RequestException as e:
            logging.error("请求失败: %s", str(e))
        except json.JSONDecodeError:
            logging.error("解析 JSON 响应失败")

    else:
        logging.info("注意----该接口不配置Mock")
        pass
